package com.tcm.ucenter.service;

import cn.hutool.core.util.ObjectUtil;
import com.base.core.exception.ServiceException;
import com.base.core.idworker.IdContext;
import com.base.core.pager.PageBean;
import com.base.core.pager.PageContext;
import com.base.core.utils.R;
import com.base.genid.generator.UidGenerator;
import com.tcm.ucenter.domain.dto.UserRechargeDTO;
import com.tcm.ucenter.domain.entity.UserRecharge;
import com.tcm.ucenter.domain.enums.BusinessCodeEnum;
import com.tcm.ucenter.mapper.UserRechargeMapper;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@DubboService(version = "0.0.1-alpha")
public class UserRechargeServiceImpl implements UserRechargeService {

    @Autowired
    private UserRechargeMapper userRechargeMapper;


    @DubboReference(version = "0.0.1-beta", group = "cached-uid", check = false, retries = 3)
    private UidGenerator uidGenerator;


    /**
     * 创建订单新增
     *
     * @param userRechargeDTO
     * @return
     */
    @Override
    public void create(UserRechargeDTO userRechargeDTO) throws ServiceException {

        if (ObjectUtil.isEmpty(userRechargeDTO.getUserId()) || userRechargeDTO.getUserId().equals(0L)) {
            R.throwFail(BusinessCodeEnum.USER_ID_NOT_FOUND);
        }
        if (ObjectUtil.isEmpty(userRechargeDTO.getAmount())
                || userRechargeDTO.getAmount().compareTo(new BigDecimal(0)) == 0) {
            R.throwFail(BusinessCodeEnum.AMOUNT_IS_NOT_EMPTY);
        }
        UserRecharge userRecharge = new UserRecharge();
        BeanUtils.copyProperties(userRechargeDTO, userRecharge);
        userRecharge.setId(uidGenerator.getUID());
        userRecharge.setOrderSn(String.valueOf(IdContext.getInstance("code").nextId()));
        userRecharge.setIsPaid(new Byte("0"));
        userRecharge.setCreateTime(LocalDateTime.now());
        userRecharge.setUpdateTime(LocalDateTime.now());
        userRecharge.setDeleted(new Byte("0"));
        try {
            int res = userRechargeMapper.insert(userRecharge);
            if (res != 1) {
                R.throwFail(BusinessCodeEnum.FAILED_TO_CREATE_ORDER);
            }
        } catch (ServiceException e) {
            R.throwOnFail(e.getResult());
        } catch (Exception e) {
            R.throwFail(e.getMessage());
        }
    }

    /**
     * 更新
     *
     * @param userRechargeDTO
     * @return
     */
    @Override
    public void update(UserRechargeDTO userRechargeDTO) throws ServiceException {

        if (ObjectUtil.isEmpty(userRechargeDTO.getId())) {
            R.throwFail(BusinessCodeEnum.ID_NOT_EXISTS);
        }
        if (userRechargeDTO.getId().equals(0L)) {
            R.throwFail(BusinessCodeEnum.ID_NOT_EXISTS);
        }

        //查询订单记录
        UserRecharge ur = userRechargeMapper.findById(userRechargeDTO.getId());
        if (ObjectUtil.isEmpty(ur) || ObjectUtil.isNull(ur)) {
            R.throwFail(BusinessCodeEnum.RECHARGE_ORDER_NOT_EXISTS);
        }
        UserRecharge userRecharge = new UserRecharge();
        BeanUtils.copyProperties(userRechargeDTO, userRecharge);
        userRecharge.setUpdateTime(LocalDateTime.now());
        userRechargeMapper.update(userRecharge);
    }

    /**
     * 单条记录查询
     *
     * @param id
     * @return
     */
    @Override
    public UserRechargeDTO findById(Long id) {
        UserRecharge userRecharge = userRechargeMapper.findById(id);
        if (ObjectUtil.isNull(userRecharge)) {
            return null;
        }
        UserRechargeDTO userRechargeDTO = new UserRechargeDTO();
        BeanUtils.copyProperties(userRecharge, userRechargeDTO);
        return userRechargeDTO;
    }

    /**
     * 获取单条数数据
     *
     * @param orderSn
     * @return
     */
    @Override
    public UserRechargeDTO findByOrderSn(String orderSn) {
        UserRecharge userRecharge = userRechargeMapper.findByOrderSn(orderSn);
        if (ObjectUtil.isNull(userRecharge)) {
            return null;
        }
        UserRechargeDTO userRechargeDTO = new UserRechargeDTO();
        BeanUtils.copyProperties(userRecharge, userRechargeDTO);
        return userRechargeDTO;
    }

    @Override
    public PageBean<UserRechargeDTO> listPageByUserId(Long userId, Long start, Long pagesize) throws ServiceException {
        Long count = userRechargeMapper.countByUserId(userId);
        PageContext.setDataCount(count);
        PageContext.setPageSize(pagesize);
        PageContext.setCurrentPage(start);
        if (count == 0) {
            return new PageBean<>(null);
        }

        List<UserRecharge> userRecharges = userRechargeMapper.listPageByUserId(userId, PageContext.getStart(), pagesize);
        PageContext.clear();
        List<UserRechargeDTO> userRechargeDTOS = userRecharges
                .stream().map(userRecharge -> {
                    UserRechargeDTO userRechargeDTO = new UserRechargeDTO();
                    BeanUtils.copyProperties(userRecharge, userRechargeDTO);
                    return userRechargeDTO;
                }).collect(Collectors.toList());
        return new PageBean<>(userRechargeDTOS);
    }


}
